package com.jgsu.farm.service.impl;

import com.jgsu.farm.entity.Message;
import com.jgsu.farm.exception.DataNotExistException;
import com.jgsu.farm.mapper.MessageMapper;
import com.jgsu.farm.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageMapper messageMapper;

    @Override
    public void add(Message message) {
        messageMapper.insert(message);
    }

    @Override
    public void delete(Integer messid) {
        Integer id = messageMapper.deleteByPrimaryKey(messid);
        if (id == 0 || id == null) {
            throw new DataNotExistException("603", "不存在该id,资讯信息删除失败");
        }
    }

    @Override
    public PageInfo<Message> selectAll(int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        List<Message> messages = messageMapper.selectAll();
        PageInfo<Message> pageInfoMessageList = new PageInfo<>(messages);
        return pageInfoMessageList;
    }


    @Override
    public void update(Message message) {
        // 1. 在更新之前根据id查询是否有要查询的数据
        Message messageId = messageMapper.selectByPrimaryKey(message.getMessid());
        if (messageId != null) {
            // 2. 如果有则，更新数据
            messageMapper.updateByPrimaryKey(message);
        } else {
            // 3, 如果没有则报错
            throw new DataNotExistException("603", "数据更新失败，不存在相应资讯信息id");
        }
    }
}
